<?php

namespace helper;

class RedisHandler
{

  private static $_instance = null;
  private static $handler = null;

  protected $options = [
      'host' => '172.21.0.11',
      'port' => 6379,
      'password' => 'tSTk56dP',
      'select' => 0,
      'timeout' => 0,
      'persistent' => false,
      'prefix' => '',
  ];

  /**
   * 初始化
   * RedisHelper constructor.
   * @param array $options
   */
  private function __construct($options = [])
  {
    if (!extension_loaded('redis')) abort(500, '未安装redis扩展');
    self::$handler = new \Redis;
    if (!empty($options)) {
      $this->options = array_merge($this->options, $options);
    }
    //本地调试用
    $this->options['host'] = env('REDIS.HOST',$this->options['host']);
    $this->options['password'] = env('REDIS.PASSWORD',$this->options['password']);

    if ($this->options['persistent']) {
      self::$handler->pconnect($this->options['host'], (int)$this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
    } else {
      self::$handler->connect($this->options['host'], (int)$this->options['port'], $this->options['timeout']);
    }
    if ('' != $this->options['password']) {
      self::$handler->auth($this->options['password']);
    }
    if (0 != $this->options['select']) {
      self::$handler->select($this->options['select']);
    }
  }

  /**
   * 单例接口
   * @param array $options
   * @return RedisHandler
   */
  public static function getInstance($options = [])
  {
    if (is_null(self::$_instance)) {
      self::$_instance = new static($options);
    }
    return self::$_instance;
  }

  /**
   * 获取redis操作句柄
   * @return \Redis|null
   */
  public function handler()
  {
    return self::$handler;
  }

  /**
   * 禁止克隆
   */
  private function __clone()
  {
  }

  /**
   * 单例切换清理
   */
  public function __destruct()
  {
    self::$handler->close();
    self::$_instance = null;
  }
}